package leetcode;

public class Solution {
    public int peakIndexInMountainArray(int[] arr) {
        int left = 0;
        int right = arr.length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;

            // 确保不会越界
            if (mid == 0) {
                if (arr[mid] < arr[mid + 1]) {
                    left = mid + 1;
                } else {
                    return mid;
                }
            } else if (mid == arr.length - 1) {
                if (arr[mid] > arr[mid - 1]) {
                    return mid;
                } else {
                    right = mid - 1;
                }
            } else {
                if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) {
                    return mid;
                } else if (arr[mid] < arr[mid + 1]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }

        // 如果只有一个元素，则返回该元素的索引
        return left;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] arr = {0, 2, 1, 0};
        System.out.println(solution.peakIndexInMountainArray(arr));
    }
}
